package com.ruoyi.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.entity.UserWechat;
import com.ruoyi.common.mapper.UserWechatMapper;
import com.ruoyi.common.service.IWechatService;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信绑定服务实现
 */
@Service
public class WechatServiceImpl implements IWechatService {

    @Autowired
    private UserWechatMapper userWechatMapper;


    // 微信小程序AppID
    /*@Value("${wechat.miniprogram.appid}")*/
    private final String appid ="wxd7f24f3c2475d5d7";

    /*@Value("${wechat.miniprogram.secret}")*/
    private final String secret = "97305e3983e1fd460f4cd0002d5a7c3d";

    // 微信获取openid的接口地址
    private static final String WECHAT_CODE2SESSION_URL = 
        "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";

    @Override
    @Transactional
    public AjaxResult bindWechat(Long userId, String code) {
        try {
            // 1. 使用code获取微信用户的openid等信息
            String url = "https://api.weixin.qq.com/sns/jscode2session";
            Map<String, Object> params = new HashMap<>(4);
            params.put("appid", appid);
            params.put("secret", secret);
            params.put("js_code", code);
            params.put("grant_type", "authorization_code");

            String resultStr = HttpUtil.get(url, params);
            JSONObject result = JSON.parseObject(resultStr);
           /* JSONObject result = JSONObject.parseObject(response.getBody());*/

            // 检查是否有错误
            if (result.containsKey("errcode") && result.getInteger("errcode") != 0) {
                return AjaxResult.error("微信授权失败：" + result.getString("errmsg"));
            }

            // 2. 解析返回结果
            String openid = result.getString("openid");
            String unionid = result.getString("unionid");
            String sessionKey = result.getString("session_key");

            // 3. 检查该openid是否已绑定其他用户
            UserWechat existingByOpenid = userWechatMapper.selectByOpenid(openid);
            if (existingByOpenid != null && !existingByOpenid.getUserId().equals(userId)) {
                return AjaxResult.error("该微信账号已绑定其他用户");
            }

            // 4. 检查当前用户是否已绑定其他微信账号
            UserWechat existingByUserId = userWechatMapper.selectByUserId(userId);
            if (existingByUserId != null) {
                // 更新现有绑定
                existingByUserId.setOpenid(openid);
                existingByUserId.setUnionid(unionid);
                existingByUserId.setUpdatedAt(LocalDateTime.now());
                userWechatMapper.updateById(existingByUserId);
            } else {
                // 创建新绑定记录
                UserWechat userWechat = new UserWechat();
                userWechat.setUserId(userId);
                userWechat.setOpenid(openid);
                userWechat.setUnionid(unionid);
                userWechat.setCreatedAt(LocalDateTime.now());
                userWechat.setUpdatedAt(LocalDateTime.now());
                userWechatMapper.insert(userWechat);
            }

            // 5. 返回成功信息（实际项目中可以获取用户微信信息后返回昵称等）
            JSONObject data = new JSONObject();
            data.put("nickname", "微信用户"); // 实际应从微信用户信息接口获取
            return AjaxResult.success("微信绑定成功", data);
        } catch (Exception e) {
            // 记录异常日志
            e.printStackTrace();
            return AjaxResult.error("微信绑定失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public AjaxResult unbindWechat(Long userId) {
        // 查询当前用户的微信绑定记录
        UserWechat userWechat = userWechatMapper.selectByUserId(userId);
        if (userWechat == null) {
            return AjaxResult.error("未绑定微信账号");
        }

        // 删除绑定记录
        int rows = userWechatMapper.deleteById(userWechat.getId());
        if (rows > 0) {
            return AjaxResult.success("微信解绑成功");
        } else {
            return AjaxResult.error("微信解绑失败");
        }
    }

    @Override
    public AjaxResult getWechatBindStatus() {
        Long userId = SecurityUtils.getUserId();
        UserWechat userWechat = userWechatMapper.selectByUserId(userId);
        JSONObject data = new JSONObject();
        
        if (userWechat != null) {
            data.put("bound", true);
            data.put("nickname", userWechat.getNickname());
            data.put("avatarUrl", userWechat.getAvatarUrl());
        } else {
            data.put("bound", false);
            data.put("nickname", null);
            data.put("avatarUrl", null);
        }
        
        return AjaxResult.success(data);
    }
}
    